package servlet;

import com.google.gson.Gson;
import org.nfentity.User;
import service.UserService;
import vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author czl
 * @Date 2024-04-22
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=UTF-8");


        // 获取客户端输入的信息
        String name = req.getParameter("uname");
        String pass = req.getParameter("upass");

        // 实例化业务对象
        UserService userService = new UserService();
        User user = userService.login(name, pass);
        ResponseData responseData = new ResponseData();

        if(user==null) {
            responseData.setCode(500);
            responseData.setMsg("错误的帐号或密码");
        } else {
            responseData.setCode(200);
            responseData.setMsg("登录成功");
            responseData.setData(user);
        }

        // 把数据序列化为 JSON 字符串返回
        String json = new Gson().toJson(responseData);

        // 把数据响应输出到客户端浏览器中
        PrintWriter out = resp.getWriter();
        out.println(json);

        out.flush();
        out.close();
    }
}
